package com.woniuxy.seckill.controller;

import com.hc.entity.Discount;
import com.hc.entity.Seckill;
import com.hc.utils.ResponseEntity;
import com.woniuxy.seckill.service.SeckillService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @BelongsProject: hc
 * @BelongsPackage: com.woniuxy.seckill.controller
 * @Author: WY
 * @CreateTime: 2022-10-25  15:37
 * @Descriprion: TODO
 * @Version: 1.0
 **/
@RestController
@RequestMapping("/seckill")
public class SeckillController {

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    RedisTemplate<String,Object> redisTemplate;

    @Autowired
    SeckillService seckillService;

    //查询商家发布的秒杀信息
    @RequestMapping("/information")
    public ResponseEntity seckillinformation(@RequestBody Seckill seckill){
        ValueOperations<String, Object> ops1 = redisTemplate.opsForValue();
        ListOperations<String, Object> ops = redisTemplate.opsForList();
        //判断redis中是否存有优惠商品的信息，没有则在数据库中查询后并存入redis中，因为发布优惠券时大量用户访问（高并发）减小数据库压力
        if(redisTemplate.hasKey("seckill1"+seckill.getShopId())){
            Object o = ops1.get("seckill1" + seckill.getShopId());
            Seckill seckill1=(Seckill)o;
            //查询redis中优惠券是否抢完了，抢完则返回数据已完，展示到界面，没完，则展示抢购中
            if(!redisTemplate.hasKey("seckill"+seckill1.getId())){
                redisTemplate.delete("seckill1"+seckill.getShopId());
                seckillService.updateStatusById(seckill1.getId());
                return new ResponseEntity("200","活动结束");
            }
            return new ResponseEntity("200","ok",o);
        }else {
            Seckill seckill1 = seckillService.findByShopId(seckill.getShopId());
            if(seckill1==null){
                return new ResponseEntity("200","暂时没有活动");
            }
            ops1.set("seckill1"+seckill.getShopId(),seckill1);
            for (int i=1;i<=seckill1.getNum();i++){
                ops.leftPush("seckill"+seckill1.getId(),i);
            }
            return new ResponseEntity("200","ok",seckill1);
        }
        
    }

    //秒杀
    @RequestMapping("/flashsale")
    public ResponseEntity flashsale(@RequestBody Discount discount){
        ListOperations<String, Object> ops = redisTemplate.opsForList();
        Object obj = ops.leftPop("seckill6");
        if(obj==null){
           return new ResponseEntity("200","活动已结束");
        }else {
            rabbitTemplate.convertAndSend("topics1","add",discount);
            return new ResponseEntity("200","已抢到");
        }
    }
}
